<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="模板名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:shippingTemplates:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:shippingTemplates:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:shippingTemplates:remove']"
          >删除</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="shippingTemplatesList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板名称" align="center" prop="name" />
      <el-table-column label="计费方式" align="center" prop="type">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 1">按件数</span>
          <span v-else-if="scope.row.type == 2">按重量</span>
          <span v-else>按体积</span>
        </template>
      </el-table-column>
      <el-table-column label="指定包邮开关" align="center" prop="appoint">
        <template slot-scope="scope">
          <span v-if="scope.row.appoint == 1">开启</span>
          <span v-else>关闭</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column prop="createTime" align="center" label="添加时间">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:shippingTemplates:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:shippingTemplates:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改运费模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form
        ref="formData"
        :model="formData"
        class="attrFrom"
        :rules="rules"
        label-width="130px"
        :inline="true"
      >
        <el-row :gutter="24" type="flex">
          <el-col :xl="18" :lg="18" :md="18" :sm="24" :xs="24">
            <el-form-item label="模板名称：" prop="name">
              <el-input
                type="text"
                placeholder="请输入模板名称"
                v-model="formData.name"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :xl="18" :lg="18" :md="18" :sm="24" :xs="24">
            <el-form-item label="计费方式：" props="state">
              <el-radio-group class="radio" v-model="formData.type">
                <el-radio :label="1">按件数</el-radio>
                <el-radio :label="2">按重量</el-radio>
                <el-radio :label="3">按体积</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
            <el-form-item class="label" label="配送区域及运费：" props="state">
              <el-table
                ref="table"
                :data="templateList"
                empty-text="暂无数据"
                border
              >
                <el-table-column
                  prop="regionName"
                  label="可配送区域"
                  width="130"
                />
                <el-table-column prop="first" label="首件" width="120">
                  <template slot="header" slot-scope="scope">
                    <span v-if="formData.type == 1">首件</span>
                    <span v-else-if="formData.type == 2">首件重量(KG)</span>
                    <span v-else>首件体积(m³)</span>
                  </template>
                  <template slot-scope="scope">
                    <span
                      ><el-input
                        :min="0"
                        type="number"
                        v-model="scope.row.first"
                    /></span>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="运费（元）" width="110">
                  <template slot-scope="scope">
                    <span
                      ><el-input
                        :min="0"
                        type="number"
                        v-model="scope.row.price"
                    /></span>
                  </template>
                </el-table-column>
                <el-table-column prop="_continue" label="续件" width="120">
                  <template slot="header" slot-scope="scope">
                    <span v-if="formData.type == 1">续件</span>
                    <span v-else-if="formData.type == 2">续件重量(KG)</span>
                    <span v-else>续件体积(m³)</span>
                  </template>
                  <template slot-scope="scope">
                    <span
                      ><el-input
                        :min="0"
                        type="number"
                        v-model="scope.row._continue"
                    /></span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="continue_price"
                  label="续费（元）"
                  width="110"
                >
                  <template slot-scope="scope">
                    <span
                      ><el-input
                        :min="0"
                        type="number"
                        v-model="scope.row.continue_price"
                    /></span>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <a
                      v-if="scope.row.regionName !== '默认全国'"
                      @click="delCity(index, 1)"
                      >删除</a
                    >
                  </template>
                </el-table-column>
              </el-table>
              <el-row type="flex" class="addTop">
                <el-col>
                  <el-button type="primary" icon="md-add" @click="addCity(1)"
                    >单独添加配送区域</el-button
                  >
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
            <el-form-item label="指定包邮：" prop="store_name">
              <el-radio-group class="radio" v-model="formData.appoint_check">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="0">关闭</el-radio>
              </el-radio-group>
              <el-table
                ref="table"
                :data="appointList"
                empty-text="暂无数据"
                border
                v-if="formData.appoint_check === 1"
              >
                <el-table-column prop="placeName" label="选择地区" />
                <el-table-column prop="a_num" label="包邮件数" width="120">
                  <template slot="header" slot-scope="scope">
                    <span v-if="formData.type == 1">包邮件数</span>
                    <span v-else-if="formData.type == 2">包邮重量(KG)</span>
                    <span v-else>包邮体积(m³)</span>
                  </template>
                  <template slot-scope="scope">
                    <span
                      ><el-input type="text" v-model="scope.row.a_num"
                    /></span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="a_price"
                  label="包邮金额（元）"
                  width="120"
                >
                  <template slot-scope="scope">
                    <span
                      ><el-input type="text" v-model="scope.row.a_price"
                    /></span>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <a
                      v-if="scope.row.regionName !== '默认全国'"
                      @click="delCity(index, 2)"
                      >删除</a
                    >
                  </template>
                </el-table-column>
              </el-table>
              <el-row type="flex" v-if="formData.appoint_check === 1">
                <el-col>
                  <el-button type="primary" icon="md-add" @click="addCity(2)"
                    >单独指定包邮</el-button
                  >
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" type="flex">
          <el-col :xl="18" :lg="18" :md="18" :sm="24" :xs="24">
            <el-form-item label="排序：" prop="store_name">
              <el-input-number
                :min="0"
                placeholder="输入值越大越靠前"
                v-model="formData.sort"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="24" type="flex">
          <el-col>
            <el-form-item prop="store_name" label=" ">
              <el-button type="primary" @click="handleSubmit">{{
                id ? "立即修改" : "立即提交"
              }}</el-button>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <city ref="city" @selectCity="selectCity" :type="type"></city>
  </div>
</template>

<script>
import {
  listShippingTemplates,
  getShippingTemplates,
  delShippingTemplates,
  addShippingTemplates,
  updateShippingTemplates,
} from "@/api/business/shippingTemplates";
import city from "./city";
var g = [
  {
    region: [
      {
        name: "默认全国",
        city_id: 0,
      },
    ],
    regionName: "默认全国",
    first: 1,
    price: 0,
    _continue: 1,
    continue_price: 0,
  },
];
export default {
  name: "ShippingTemplates",
  data() {
    return {
      type: 1,
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运费模板表格数据
      shippingTemplatesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        regionInfo: null,
        appoint: null,
        appointInfo: null,
        sort: null,
      },
      // 表单参数
      formData: {},
      templateList: g,
      appointList: [],
      // 表单校验
      rules: {
        id: [{ required: true, message: "模板ID不能为空", trigger: "blur" }],
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "计费方式不能为空", trigger: "change" },
        ],
        regionInfo: [
          { required: true, message: "地域以及费用不能为空", trigger: "blur" },
        ],
        appoint: [
          { required: true, message: "指定包邮开关不能为空", trigger: "blur" },
        ],
        appointInfo: [
          { required: true, message: "指定包邮内容不能为空", trigger: "blur" },
        ],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
      },
    };
  },
  components: { city },

  created() {
    this.getList();
  },
  methods: {
    // 删除
    delCity(index, type) {
      if (type === 1) {
        this.templateList.splice(index, 1);
      } else {
        this.appointList.splice(index, 1);
      }
    },
    selectCity: function (data, type) {
      let cityName = data
        .map(function (item) {
          return item.name;
        })
        .join(";");
      switch (type) {
        case 1:
          this.templateList.push({
            region: data,
            regionName: cityName,
            first: 1,
            price: 0,
            _continue: 1,
            continue_price: 0,
          });
          break;
        case 2:
          this.appointList.push({
            place: data,
            placeName: cityName,
            a_num: 0,
            a_price: 0,
          });
          break;
      }
    },
    /** 查询运费模板列表 */
    getList() {
      this.loading = true;
      listShippingTemplates(this.queryParams).then((response) => {
        this.shippingTemplatesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.formData = {
        id: null,
        type: 1,
        sort: 0,
        name: "",
        appoint_check: 0,
      };
      this.resetForm("formData");
      this.appointList = [];
      this.addressView = false;
      this.templateList = [
        {
          region: [
            {
              name: "默认全国",
              city_id: 0,
            },
          ],
          regionName: "默认全国",
          first: 1,
          price: 0,
          _continue: 1,
          continue_price: 0,
        },
      ];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    addCity(type) {
      this.$refs.city.addressView = true;
      this.type = type;
      this.$refs.city.getCityList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加运费模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getShippingTemplates(id).then((response) => {
        this.formData = response.data;
        this.formData.appoint_check = response.data.appoint;
        this.templateList = JSON.parse(response.data.regionInfo);
        this.open = true;
        this.title = "修改运费模板";
      });
    },
    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["formData"].validate((valid) => {
    //     if (valid) {
    //       if (this.formData.id != null) {
    //         updateShippingTemplates(this.formData).then((response) => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addShippingTemplates(this.formData).then((response) => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    submitForm: function () {
      let that = this;
      if (!that.formData.name.trim().length) {
        return this.$message({
          message: "请填写模板名称",
          type: "error",
        });
      }
      for (let i = 0; i < that.templateList.length; i++) {
        if (that.templateList[i].first <= 0) {
          return this.$message({
            message: "首件/重量/体积应大于0'",
            type: "error",
          });
        }
        if (that.templateList[i].price < 0) {
          return this.$message({
            message: "运费应大于等于0",
            type: "error",
          });
        }
        if (that.templateList[i].continue <= 0) {
          return this.$message({
            message: "续件/重量/体积应大于0",
            type: "error",
          });
        }
        if (that.templateList[i].continue_price < 0) {
          return this.$message({
            message: "续费应大于等于0",
            type: "error",
          });
        }
      }
      if (that.formData.appoint_check === 1) {
        for (let i = 0; i < that.appointList.length; i++) {
          if (that.appointList[i].a_num <= 0) {
            return this.$message({
              message: "包邮件数应大于0",
              type: "error",
            });
          }
          if (that.appointList[i].a_price < 0) {
            return this.$message({
              message: "包邮金额应大于等于0",
              type: "error",
            });
          }
        }
      }
      let data = {
        id: this.formData.id,
        appoint_info: that.appointList,
        region_info: that.templateList,
        sort: that.formData.sort,
        type: that.formData.type,
        name: that.formData.name,
        appoint: that.formData.appoint_check,
      };
      this.$refs["formData"].validate((valid) => {
        if (valid) {
          if (this.formData.id != null) {
            addShippingTemplates(data).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShippingTemplates(data).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除该运费模板？")
        .then(function () {
          return delShippingTemplates(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/shippingTemplates/export",
        {
          ...this.queryParams,
        },
        `shippingTemplates_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
